import serial
from binascii import unhexlify
import pymodbus.utilities as uti
import redis
import time
import statistics

if __name__ == '__main__':
    r = redis.Redis(db=0)
    r.set('radar_3', 'off')     # dmesg | grep tty

    ser = serial.Serial('/dev/ttyUSB3', 115200)
    ser.readline()

    distance_l = []

    while True:
        if r.get('radar_3').decode("utf-8") == 'on':
            result = ser.readline()
            if len(result) == 19:
                result = result[1:-2]

                checksum = result[-4:]
                data = result[:-4]

                if uti.computeCRC(unhexlify(data)) == int(checksum, 16):
                    distance = int(data[-4:], 16) + 20

                    # distance_l.append(distance)
                    print(distance)

                    r.set('radar_2_distance', int(distance))

        else:
            time.sleep(0.5)
            distance_l = []

